package org.OpenGeoPortal.Servlet;

import java.io.*;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.Logger;

//import com.esri.aims.mtier.io.ConnectionProxy;
import com.javaexchange.dbConnectionBroker.DbConnectionBroker;

// HGL specific imports
import edu.harvard.hul.ois.hgl.geoserver.rest.GsREST;
import edu.harvard.hul.ois.hgl.geoserver.rest.gsUtils;
import edu.harvard.hul.ois.hgl.util.HGLUtilities;

public class RemoteServiceStarter extends HttpServlet {
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RemoteServiceStarter() {
        super();
    }
    
	private static final long serialVersionUID = 1L;
	private static boolean _responseCode = false;
	private String mailMessage = "holder";

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost( request, response );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html");
		
        // Get the session context
        HttpSession session = request.getSession();

		String thisIP = request.getRemoteAddr();
		String validationKey = request.getParameter("ValidationKey");
		String genericLogMessage = "....all processing vars validated...";
		String layerToAdd = request.getParameter("AddLayer").toUpperCase();
		String serviceName = "null";
		int geometryType = 51;
		
		ServletContext theContext = getServletContext();

		// Just set a default
		String servername = "dixon.hul.harvard.edu";
		
		try {
			InetAddress addr = InetAddress.getLocalHost();
			if (addr.getHostName() != null)
				servername = addr.getHostName();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Test the passkey
		boolean passkeyOK = false;
		
		passkeyOK = isValidKey(validationKey);
		
		if (!passkeyOK) {
			
			// Maybe a little harsh...
			session.invalidate();
			
			return;
		}
		
        // Set up the connection to Geoserver
        GsREST myGSConnection = new GsREST("http://"+servername+":8080/geoserver","x","x");
        
        /* TEMPORARY --- TEST */
        serviceName = layerToAdd;
        String _owner = "SDE";
        String _layerName = "0";
        DecimalFormat df = new DecimalFormat("########.#######");
        
        try {
        			
   			_owner = HGLUtilities.getSDELayerOwner(layerToAdd);
      	    _layerName = layerToAdd;
      	    int lID = HGLUtilities.getSDELayerID(_layerName);
      	    geometryType = HGLUtilities.getLayerGeometryType(lID);
      	    
      	    String bbox = "";
      	    String bbox2 = "";
      	    String bbox3 = "";
      	    double[] fromGSN = HGLUtilities.getLayerBoundingCoordsFromGS_NEW(lID);
			double[] a1, a2;
			
			a1 = HGLUtilities.ll2meters(fromGSN[1], fromGSN[0]);
			a2 = HGLUtilities.ll2meters(fromGSN[3], fromGSN[2]);

			bbox = "bbox="+ df.format(a1[0])+","+df.format(a1[1])+","+df.format(a2[0])+","+df.format(a2[1]);
			bbox2 = df.format(a1[0])+","+df.format(a1[1])+","+df.format(a2[0])+","+df.format(a2[1]);
			bbox3 = fromGSN[0]+","+fromGSN[1]+","+fromGSN[2]+","+fromGSN[3];
			
    		if (geometryType != 50) {
        			
	        	// This is a vector layer....

    			// Does it already exist as a Geoserver layer? If so just skip creating it but
	        	// make sure it is added to the list of layers for the map legend later.
				if (!gsUtils.isLayerPublished(myGSConnection.getFeatureType("sde", "alcott"), _owner+"."+_layerName)) {
					myGSConnection.createFeatureType("sde", "alcott", _owner+"."+_layerName);
					gsUtils.appendToTilecacheConfigFile("sde", _owner, _layerName, bbox);
				} 
					
    		} else if (geometryType == 50) {

    			// This is a raster layer....
					
				//You need to come up with a new name for the data store. Use sde## 
				int storeID = 7;
				
				// So, use a random # as it can't be worse than the above.
				Random randGen = new Random();
				storeID = randGen.nextInt(99000);
				System.out.println("Coverage store set to sde"+storeID);
				
				boolean storeExists = false;
				if (myGSConnection.getLayerNames().contains(_owner+"."+_layerName)) {
					storeExists = true;
					//System.out.println(_owner+"."+_layerName+" already exists.");
				}

				if (!storeExists) {
					myGSConnection.createSDECoverageStore("cite","sde"+storeID, _owner, _layerName);
					myGSConnection.publishArcSDERaster("cite", "sde"+storeID, "x", "sde", "alcott.hul.harvard.edu", _owner, _layerName, "5157");
					gsUtils.appendToTilecacheConfigFile("cite", _owner, _layerName, bbox);
					System.out.println("Should have added "+_owner+"."+_layerName+" to cite:sde"+storeID);
				} else {
					// gsUtils won't append if it is already in there
					gsUtils.appendToTilecacheConfigFile("cite", _owner, _layerName, bbox);
				}
    		}
		
        } catch (Exception e) {
        	e.printStackTrace();
        }
        

	}
	
    /** Validate if a text string is formatted well as an email
     *@param String emailA Address to check
     *@return boolean True or False
     */
    public static boolean isValidEmail(String email) {
        
      //Set the email pattern string
      Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

      //Match the given string with the pattern
      Matcher m = p.matcher(email);

      //check whether match is found 
      boolean matchFound = m.matches();

      if (matchFound)
        return true;
      else
        return false;

    }
	
    /* We are using a passkey as a primitive method to validate a start service request
     * 
     */
    private boolean isValidKey(String validationKey)  throws IOException {
    	boolean OK = false;
    	
    	if (validationKey.equals("OPENGEOPORTALROCKS")) {
    		OK = true;
    	} else {
    		OK = false;
    	}
    	
    	return OK;
    	
    }
    
    private boolean isTrustedIP(String userIP) throws IOException {
    	
    	String trustedIPs = "124.247.0.0;120.120.5.5";
    	
    	if (trustedIPs.contains(userIP)) {
    		//return true;
    	} else {
    		//return false;
    	}
    	
    	// For beta testing let them all through
    	return true;
    	
    }
	  
}

